//
//  NetworkTool.swift
//  DrawerBasicsSwift
//
//  Created by Arrse on 2017/10/18.
//  Copyright © 2017年 Modobay. All rights reserved.
//

import Alamofire

func net_delay(time: TimeInterval, completionHandler: @escaping ()-> Void) {
    DispatchQueue.main.asyncAfter(deadline: .now() + time) {
        completionHandler()
    }
}

func URLCachePath(_ name:String) -> URL {
   let documentsURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0]
   let fileURL = documentsURL.appendingPathComponent("1meeting/"+name)
   return fileURL
}

func NET_main(completionHandler: @escaping ()-> Void){
    
        DispatchQueue.main.async {
            // 更新UI操作
            completionHandler()
            
        }
}


class NetworkTool: NSObject {
    
    //设置单例
    static let shared:NetworkTool  = {
        let instance = NetworkTool()
        return instance
    }()
}

//设置请求头
let requestHeader:HTTPHeaders = [
    "Content-Type" :"text/html",
    //"Content-Type": "application/json",
    //"Content-Type": "application/x-www-form-urlencoded",
    //"Accept": "application/json",
    //"Accept": "multipart/form-data"
    
    //"Accept": "application/json",
    //"Content-Type" :"application/json"
]

enum MethodType {
    case get
    case post
}


extension NetworkTool {
    
    class func requestData(type: MethodType,
                           URLString: String,
                           parameters: [String : Any]? = nil,
                           finishCallback: @escaping (_ result: AnyObject) -> (),
                           failture: @escaping (_ error : Error)->()) {
        
        //1. 获取类型
        let method = type == .get ? HTTPMethod.get : HTTPMethod.post
        
        //2. 发送请求(encode:- JSONEncoding.default,URLEncoding.queryString)
        Alamofire.request(URLString, method: method, parameters: parameters).responseJSON { (response) in
            
            //3. 获取数据
            guard let result = response.result.value else {
                print(response.result.error!)
                failture(response.result.error!)
                return
            }
            
            //4. 将结果返回
            finishCallback(result as AnyObject)
        }
        
    }
}

extension NetworkTool {
    //MARK: - 请求管理者
    func afManager() -> SessionManager {
        let manager = Alamofire.SessionManager.default
        manager.session.configuration.timeoutIntervalForRequest = 10 //设置请求时长
        return manager
    }
    
    //MARK: - GET 请求
    func getRequest(urlString: String, params : [String : Any]?, success : @escaping (_ response : [String : AnyObject])->(), failture : @escaping (_ error : Error)->()) {
        
        //拼接请求接口, 发送请求
        //let urlStr = String(format:"%@%@", api_Domain, urlString)
        afManager().request(urlString, method: .get, parameters: params,encoding: URLEncoding.queryString, headers:[:]).responseJSON { (response) in
            /*这里使用了闭包*/
            
            switch response.result {
            case .success:
                if let value = response.result.value as? [String: AnyObject] {
                    //let json = JSON(value)
                    //ARLog(json)
                    success(value)
                }
                
            case .failure(let error):
                //ARLog("error:\(error)")
                failture(error)
            }
        }
    }
    
    //MARK: - POST 请求
    func postRequest(urlString : String, params : [String : Any]?, success : @escaping (_ response : [String : AnyObject])->(), failture : @escaping (_ error : Error)->()) {
        
        
        //拼接请求接口, 发送请求
        //let urlStr = String(format:"%@%@", api_Domain, urlString)
        afManager().request(urlString, method: HTTPMethod.post, parameters: params, encoding: JSONEncoding.default, headers:[:]).responseJSON { (response) in

            switch response.result{
            case .success:
                if let value = response.result.value as? [String: AnyObject] {
                    //let json = JSON(value)
                    //ARLog(json)
                    success(value)
                }
            case .failure(let error):

                //ARLog("error:\(error)")
                failture(error)
            }
        }
    }
    
    
    
    
    //MARK: - POST 请求
    func postString(urlString : String, params : [String : Any]?, success : @escaping (_ response : String)->(), failture : @escaping (_ error : Error)->()) {
        
        
        //拼接请求接口, 发送请求
        //let urlStr = String(format:"%@%@", api_Domain, urlString)
        afManager().request(urlString, method: HTTPMethod.post, parameters: params, encoding: URLEncoding.queryString, headers:requestHeader).responseString { (response) in
        
            
            switch response.result{
                
            case .success:
                if let value = response.result.value {
                    //let json = JSON(value)
                    //ARLog(json)
                    success(value)
                }
            case .failure(let error):
                
                //ARLog("error:\(error)")
                failture(error)
            }
        }
        
    }
    
    //下载
    //.cancel()停止，.suspend()暂停，resume()继续
    @discardableResult
    class func download(urlString: String,fileBaseUrl:URL,fileName: String?=nil,closure: @escaping (_ fractionCompleted : Double)->Void ,completionHandler: @escaping (DownloadResponse<Data>) -> Void) -> DownloadRequest {
        
        //指定下载路径和保存文件名
        let destination: DownloadRequest.DownloadFileDestination = { _, response in
            //两个参数表示如果有同名文件则会覆盖，如果路径中文件夹不存在则会自动创建
            let name = (fileName == nil) ? response.suggestedFilename!:fileName!
            let url = fileBaseUrl.appendingPathComponent(name)
            return (url, [.removePreviousFile, .createIntermediateDirectories])
        }
        
        //开始下载
        let request = Alamofire.download(urlString, to: destination)
        
        request.downloadProgress { progress in
            print("当前进度: \(progress.fractionCompleted)")
            closure(progress.fractionCompleted)
        }.responseData { response in
            if let data = response.result.value {
                print("下载完毕!,\(data)")
            }
            completionHandler(response)
        }
        
        /////////////////////////
        /*
        Alamofire.download(urlString, to: destination)
            .response { response in
                completionHandler(response)
        }
         */
        return request
    }
    
}








